package com.ringtheweb.common.util.crypto;

import java.text.ParseException;


/**
 * SIM number verification
 * 
 * @author ldewavri
 * 
 */
public class CheckSIM {
	
	/** This helper class should not be instanciated */
	 private CheckSIM() {/* EMPTY */}

	/**
	 * Verification using the Luhn algorithm. 
	 * More information on : http://www.semaphorecorp.com/misc/cc.html 
	 *  
	 * @param simNumber
	 * @return true if the SIM number is valid
	 * @throws ParseException if the SIM number does not have 19 characters.
	 */
	 public static boolean verifieAlgorythmeLuhn(String simNumber)
	 	throws ParseException
	 {
		char[] charArry = simNumber.toCharArray();
		int nbChar = charArry.length;
		int SIM_DIGIT_NUM = 19;
		if ( nbChar != SIM_DIGIT_NUM )
		{
			throw new ParseException(simNumber, SIM_DIGIT_NUM);			
		}
	
		int sum = 0;
		int multiplier = 1;
		for (int i=(nbChar-1); i>=0; i--)
		{
			int car = new Integer(String.valueOf(charArry[i])).intValue();
			int product = car * multiplier;
			sum = sum + (product / 10) + (product % 10);
			multiplier = 3 - multiplier; // 1->2, 2->1
		}
		return ((sum % 10) == 0);
	}
}
